import {defineStore} from "pinia";
import {ref} from "vue";
import {useRouter} from "vue-router";

export class FrameTab {
    constructor(key = '', name = '', router = '', active = false) {
        this.key = key
        this.name = name
        this.router = router
        this.active = active
    }

}

export const useFrameTabStore = defineStore('frame-tab', () => {
    const router = useRouter()
    const tabs = ref([])

    const hasActive = () => {
        for (let i = 0; i < tabs.value.length; i++) {
            if (tabs.value[i].active) {
                return true
            }
        }
        return false
    }

    const active = async (k = '') => {
        for (let i = 0; i < tabs.value.length; i++) {
            tabs.value[i].active = tabs.value[i].key === k
            if (tabs.value[i].active) {
                await router.push({name: tabs.value[i].router})
            }
        }
    }

    const exist = (k = '') => {
        for (let i = 0; i < tabs.value.length; i++) {
            if (tabs.value[i].key === k) {
                return true
            }
        }
        return false
    }
    const add = async (v, act = true, unshift = false,) => {
        if (!exist(v.index)) {
            const tabItem = menu2frameTab(v)
            if (unshift) {
                tabs.value.unshift(tabItem)
            } else {
                tabs.value.push(tabItem)
            }
        }
        if (act) {
            await active(v.index)
        }

    }

    const menu2frameTab = (v) => {
        return new FrameTab(v.index, v.name, v.router)
    }

    const remove = async (k = '') => {
        if (tabs.value.length === 1) {
            return
        }
        let idx
        for (idx = 0; idx < tabs.value.length; idx++) {
            if (tabs.value[idx].key === k) {
                break
            }
        }
        tabs.value.splice(idx, 1)
        await active(tabs.value[tabs.value.length - 1].key)
    }


    return {tabs, add, remove, exist, active, hasActive}
})